import axios from 'axios';
import cookie from 'js-cookie';
import { router } from '@/router/permission';
import {
  Toast
} from 'vant';
import qs from 'qs';

//axios配置
const http = axios.create({
  // baseURL: 'http://47.96.152.132:8888/api' ,
  baseURL:process.env.NODE_ENV === 'production' ? '/api' : '/api',
  timeout: 30000
})


function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
     var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
     return v.toString(16).toLowerCase();
  });
}

//request 请求拦截器
http.interceptors.request.use(
  config => {
    const method = config.method;
	config.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
		
    const token = localStorage.getItem('token');
    const clientInfo = localStorage.getItem('clientInfo');
    if(token) {
        config.headers.common['Authorization'] = token;
    }
    if(clientInfo) {
        // 信息从 app拿取
        config.headers.common['client-info'] = clientInfo;
    }else {
        // h5单独页面——自己生成
        let clientInfoH5 = '', chspApiUuid = cookie.get('_uuid');
        if(chspApiUuid) {
           clientInfoH5 = JSON.stringify({
            platform: "Web",
            device_no: chspApiUuid
          });
        }else {
          const uuidv4Str = uuidv4();
          const uuid = JSON.stringify({
            platform: "Web",
            device_no: uuidv4Str
          })
          cookie.set('_uuid', uuidv4Str)
          clientInfoH5 = uuid;
        }
        
        config.headers.common['client-info'] = clientInfoH5;
    }
    
    return config
  }, error => {
    return Promise.reject(error)
  }
)



//response 拦截,响应数据操作
http.interceptors.response.use((res) => {
    if (res.data.code !== 200) {
        if(res.data.code === 100) {
            
        }else if(res.data.code === 401) {
            localStorage.clear();
            router.push({
              name: 'login'
            })
        }else {
            Toast(res.data.message);
        }
        return Promise.reject(res)
    }
  return res.data;
}, (error) => {
  console.log(error.request.status, '接口报错状态码');
    if(error.request.status === 401) {
        localStorage.clear();
        router.push({
          name: 'login'
        })
    }else {
        Toast("网络不稳定，请稍后再试");
    }
 
  return Promise.reject(error);
});

export default http
